package device

import (
	"context"
	"net/http"

	"go-zero-admin/apps/modules/iot/cmd/api/internal/svc"
	"go-zero-admin/apps/modules/iot/cmd/api/internal/types"
	"go-zero-admin/apps/modules/iot/cmd/rpc/iotpb"
	"go-zero-admin/pkg/ctxdata"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type ListDeviceLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	r      *http.Request
}

func NewListDeviceLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *ListDeviceLogic {
	return &ListDeviceLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		r:      r,
	}
}

func (l *ListDeviceLogic) ListDevice(req *types.ListDeviceReq) (resp *types.ListDeviceResp, err error) {
	deviceListResp, err := l.svcCtx.DeviceRpc.GetDeviceList(l.ctx, &iotpb.GetDeviceListReq{
		Page: &iotpb.PageReq{
			DateRange: req.DateRange,
			PageNum:   req.PageNum,
			PageSize:  req.PageSize,
			IsPage:    true,
		},
		Name:            req.Name,
		State:           req.State,
		IsDataScope:     true,
		DataScopeUserId: ctxdata.GetUidFromCtx(l.ctx),
	})
	if err != nil {
		return nil, err
	}

	// 处理数据
	deviceList := make([]*types.IotDevice, 0)
	for _, v := range deviceListResp.GetList() {
		var product types.IotDevice
		_ = copier.Copy(&product, v)
		deviceList = append(deviceList, &product)
	}

	return &types.ListDeviceResp{
		PageResp: &types.PageResp{
			CurrentPage: deviceListResp.GetPage().GetCurrent(),
			Total:       deviceListResp.GetPage().GetTotal(),
		},
		List: deviceList,
	}, nil
}
